import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
// 创建仓库
const store = new Vuex.Store({
  state: {
    num: 10
  },
  mutations: {
    add_num (state, n) {
      // state num自增
      state.num += n
    },
    reduce_num (state, n) {
      state.num -= n
    },
    init_num (state, n) {
      state.num = n
    }
  },
  actions: {
    set_num_async ({ commit }, n) {
      // context参数就是 store这个对象
      // 参数2可以省略 dispatch 这个方法action时传的参数

      setTimeout(() => {
        const num = n
        commit('init_num', num)
      }, 2000)
    }
  },
  getters: {
    doubleNum: (state) => {
      return state.num * 2
    }
  }
})

export default store
